package com.dnndo.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.dnndo.common.annotation.Log;
import com.dnndo.common.core.controller.BaseController;
import com.dnndo.common.core.domain.AjaxResult;
import com.dnndo.common.core.domain.PageResult;
import com.dnndo.common.core.domain.R;
import com.dnndo.common.core.domain.entity.SysUser;
import com.dnndo.common.enums.BusinessType;
import com.dnndo.common.utils.SecurityUtils;
import com.dnndo.common.utils.bean.BeanDtoVoUtil;
import com.dnndo.system.domain.SysUserRole;
import com.dnndo.system.domain.dto.*;
import com.dnndo.system.domain.vo.SysUserVO;
import com.dnndo.system.mapper.SysUserRoleMapper;
import com.dnndo.system.service.ISysUserService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public PageResult<SysUserVO> list(SysUserDTO dto)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(dto);
        return PageResult.pageOk(BeanDtoVoUtil.listVo(list, SysUserVO.class), new PageInfo<>(list).getTotal());
    }

  @GetMapping("/listR")
  public PageResult<SysUserVO> listR(SysUserDTO dto)
  {
    startPage();
    List<SysUser> list = userService.selectUserListR(dto);
    return PageResult.pageOk(BeanDtoVoUtil.listVo(list, SysUserVO.class), new PageInfo<>(list).getTotal());
  }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:getInfo')")
    @GetMapping("/getInfo")
    public R<SysUserVO> getInfo(@ApiParam (value = "用户ID",required = true) Long userId)
    {
        SysUser sysUser = userService.selectUserById(userId);
        return R.ok(BeanDtoVoUtil.convert(sysUser, SysUserVO.class));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysUserInsertDTO dto) {
        //根据手机号查询是否有这个用户
        SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, dto.getPhonenumber())
                .eq(SysUser::getDelFlag, 0));
        if (sysUser != null) {
            return error("新增失败,手机号已存在");
        }
        SysUser user = BeanDtoVoUtil.convert(dto, SysUser.class);
        // 查询普通用户角色信息
//        SysRole role = roleService.getOne(new LambdaQueryWrapper<SysRole>()
//                .eq(SysRole::getRoleType, RoleConstants.ROLE_TYPE_COMMON)
//                .eq(SysRole::getStatus, RoleConstants.ROLE_STATUS_NORMAL)
//                .eq(SysRole::getDelFlag, 0)
//                .orderByDesc(SysRole::getCreateTime)
//                .last("limit 1"));
//        //如果没有普通角色，直接返回注册失败
//        if (role == null) {
//            return error("新增失败,请联系系统管理人员");
//        }
        user.setUserName(dto.getPhonenumber());
        user.setCreateBy(getUserId().toString());
        user.setDelFlag("0");
        user.setCreateTime(new Date());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 插入用户信息
        boolean save = userService.save(user);
        if (save) {
            // 插入用户角色
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(dto.getRoleId());
            userRole.setUserId(user.getUserId());
            userRoleMapper.insert(userRole);
        }
        return toAjax(save);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUserUpdateDTO dto)
    {
        //根据手机号和用户id查询用户信息
        long count = userService.count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, dto.getPhonenumber())
                .ne(SysUser::getUserId, dto.getUserId())
                .eq(SysUser::getDelFlag, 0));
        if (count > 0) {
            return error("修改失败,手机号已存在");
        }
        SysUser sysUser = BeanDtoVoUtil.convert(dto, SysUser.class);
        sysUser.setUpdateBy(getUserId().toString());
        sysUser.setUpdateTime(new Date());
        sysUser.setUserName(dto.getPhonenumber());
        //修改用户角色表
        userService.updateUserRole(sysUser.getUserId(),sysUser.getRoleId());
        return toAjax(userService.updateById(sysUser));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:del')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @GetMapping("/del")
    public AjaxResult del(@ApiParam(value = "用户ID",required = true) Long userId)
    {
        if (userId.equals(getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserById(userId));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody @Validated SysUserResetPwdDTO dto)
    {
        SysUser sysUser = BeanDtoVoUtil.convert(dto, SysUser.class);
        userService.checkUserAllowed(sysUser);
        userService.checkUserDataScope(sysUser.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUser.setUpdateBy(getUserId().toString());
        sysUser.setUpdateTime(new Date());
        return toAjax(userService.resetPwd(sysUser));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:changeStatus')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody @Validated SysUserUpdStatusDTO dto)
    {
        //不允许操作自己的状态
        if (SecurityUtils.getUserId().equals(dto.getUserId())) {
            return error("不允许修改当前用户状态");
        }
        SysUser user = BeanDtoVoUtil.convert(dto, SysUser.class);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUserId().toString());
        user.setUpdateTime(new Date());
        return toAjax(userService.updateUserStatus(user));
    }


}
